<?php

namespace app\common\services;

use yii\helpers\Html;

class UtilService
{
    public static function getRootPath()
    {
        $vendor_path = \Yii::$app->vendorPath;

        return dirname($vendor_path);
    }

    public static function encode($dispaly_text)
    {
        return Html::encode($dispaly_text);
    }

    public static function getIP()
    {
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }

        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    }

    public static function isWechat()
    {
        $ug = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (stripos($ug, 'micromessenger') !== false) {
            return true;
        }

        return false;
    }

    public static function getRand($data)
    {
        $result = [];
        foreach ($data as $key => $val) {
            $arr[$key] = $val['weight'];
        }
        // 概率数组的总概率
        $proSum = array_sum($arr);
        asort($arr);
        // 概率数组循环
        foreach ($arr as $k => $v) {
            $randNum = mt_rand(0, $proSum);
            if ($randNum <= $v) {
                $result = $data[$k];
                break;
            } else {
                $proSum -= $v;
            }
        }

        return $result;
    }

    public static function ToXml($values)
    {
        if (!is_array($values) || count($values) <= 0) {
            return false;
        }

        $xml = '<xml>';
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
            } else {
                $xml .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>';
            }
        }
        $xml .= '</xml>';

        return $xml;
    }

    public static function FromXml($xml)
    {
        if (!$xml) {
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);

        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    public static function getRandChar($length = 6)
    {
        $str = null;
        $strPol = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    public static function ToUrlParams($values)
    {
        $buff = '';
        foreach ($values as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                $buff .= $k . '=' . $v . '&';
            }
        }

        $buff = trim($buff, '&');

        return $buff;
    }

    public static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $weixin_info = \Yii::$app->params['weixin'];
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        //如果有配置代理这里就设置代理
        if ($weixin_info['CURL_PROXY_HOST'] != '0.0.0.0' && $weixin_info['CURL_PROXY_PORT'] != 0) {
            curl_setopt($ch, CURLOPT_PROXY, $weixin_info['CURL_PROXY_HOST']);
            curl_setopt($ch, CURLOPT_PROXYPORT, $weixin_info['CURL_PROXY_PORT']);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, false);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($useCert == true) {
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, '/www/wwwroot/szhqg.horsevision.cn/web/cert/apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, '/www/wwwroot/szhqg.horsevision.cn/web/cert/apiclient_key.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);

            return $data;
        } else {
            $error = curl_errno($ch);
            var_dump($error);
            curl_close($ch);

            return false;
            //throw new \WxPayException("curl出错，错误码:$error");
        }
    }
}
